import React, { useEffect,useState } from 'react'

interface Props {
    
}


    const SpeechToText:React.FC<SpeechToTextProps>=()=>{
        const [transcript, setTranscript] = useState<string>('');
        let recognition:SpeechRecognition | webkitSpeechRecognition | null = null;
        useEffect(()=>{
            //检查浏览器是否支持语音识别
            if('SpeechRecognition' in window || 'webkitSpeechRecognition' in window){
                recognition=new((window as any).SpeechRecognition || (window as any).webkitSpeechRecognition)();
                recognition.lang='en-Us';//设置语言
                recognition.interimResults=false;//是否返回中间结果

                recognition.onresult=(event:SpeechRecognitionEvent)=>{
                    const last=event.results.length-1;
                    const text=event.results[last][0].transcript;
                    setTranscript(text);
                };
                recognition.onerror=(event:SpeechRecognitionError)=>{
                    console.log('111',event.error);
                };
                recognition.onend=()=>{
                    console.log('end');
                    
                };
                recognition.start();
             
            }
            else{
                console.log('浏览器不支持语音识别');
            }
            return()=>{
                if(recognition){
                    recognition.stop();
                }
                
            }
        },[]);
       return (
        <div>
            <h3>语音转文字</h3>
            <p>{transcript}</p>
        </div>
    )
    }